import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

# 2. 生成3分类的数据集
X, y = make_classification(n_samples=1000, n_features=5, n_informative=2, n_redundant=3,
                           n_classes=3, n_clusters_per_class=1, random_state=42)
# 3. 标准化数据
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 4. 使用PCA进行降维
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)

# 5. 可视化降维后的数据
# 颜色列表
colors = ['navy', 'turquoise', 'darkorange']

# 绘制PCA降维后的数据
plt.figure(figsize=(8, 6))
for color, i in zip(colors, [0, 1, 2]):
    plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], alpha=0.8, color=color,
                label=f'Class {i}')
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('PCA of 3-Class Synthetic Dataset')
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.grid(True)
plt.show()
